// 设置全局错误处理器
process.on('uncaughtException', (error) => {
    console.error('未捕获的异常:', error);
    console.error('错误堆栈:', error.stack);
});

process.on('unhandledRejection', (reason, promise) => {
    console.error('未处理的Promise拒绝:', reason);
    if (reason instanceof Error) {
        console.error('错误堆栈:', reason.stack);
    }
});

const path = require('path');
const fs = require('fs');
const { customRequire } = require('./utils.js');
const { sendMonitoringData } = require('./user-data.js');

// 导入 Google Sheets API 相关模块
let { google } = customRequire('googleapis');
if (!google) {
    try {
        google = require('googleapis').google;
    } catch (err) {
        console.error('无法加载 googleapis:', err.message);
    }
}

// 加载服务账户凭证
const CREDENTIALS_PATH = path.join(__dirname, 'swift-synthesis-450101-j7-08e26bb7334e.json');
let credentials = null;

try {
    const credentialsContent = fs.readFileSync(CREDENTIALS_PATH, 'utf8');
    credentials = JSON.parse(credentialsContent);
    console.log('成功加载 Google Sheets 凭证文件');
} catch (error) {
    console.error('加载凭证文件失败:', error.message);
}

// 初始化 Google Sheets API 客户端
let sheets = null;
let auth = null;

async function initializeGoogleSheetsAPI() {
    try {
        if (!credentials) {
            throw new Error('凭证文件未加载');
        }

        // 创建 JWT 认证客户端
        auth = new google.auth.JWT(
            credentials.client_email,
            null,
            credentials.private_key,
            ['https://www.googleapis.com/auth/spreadsheets']
        );

        // 授权客户端
        await auth.authorize();
        console.log('Google Sheets API 认证成功');

        // 创建 Sheets API 实例
        sheets = google.sheets({ version: 'v4', auth });
        
        return true;
    } catch (error) {
        console.error('初始化 Google Sheets API 失败:', error.message);
        return false;
    }
}

// 获取工作表名称列表
async function getSheetNames(spreadsheetId) {
    try {
        if (!sheets) {
            const initialized = await initializeGoogleSheetsAPI();
            if (!initialized) {
                throw new Error('Google Sheets API 初始化失败');
            }
        }

        const response = await sheets.spreadsheets.get({
            spreadsheetId: spreadsheetId,
        });

        const sheetNames = response.data.sheets.map(sheet => sheet.properties.title);
        console.log('获取到的工作表名称:', sheetNames);
        return sheetNames;
    } catch (error) {
        console.error('获取工作表名称失败:', error.message);
        throw error;
    }
}

// 读取行数据
async function readRowData(spreadsheetId, range) {
    try {
        if (!sheets) {
            const initialized = await initializeGoogleSheetsAPI();
            if (!initialized) {
                throw new Error('Google Sheets API 初始化失败');
            }
        }

        const response = await sheets.spreadsheets.values.get({
            spreadsheetId: spreadsheetId,
            range: range,
        });

        const rows = response.data.values || [];
        console.log(`从范围 ${range} 读取到 ${rows.length} 行数据`);
        return rows;
    } catch (error) {
        console.error('读取行数据失败:', error.message);
        throw error;
    }
}

// 更新部分列数据
async function updatePartialColumns(spreadsheetId, sheetName, plmCode, updates, searchRange) {
    try {
        if (!sheets) {
            const initialized = await initializeGoogleSheetsAPI();
            if (!initialized) {
                throw new Error('Google Sheets API 初始化失败');
            }
        }

        // 首先读取数据以找到匹配的行
        const data = await readRowData(spreadsheetId, searchRange);
        let targetRowIndex = -1;

        // 查找包含 PLM Code 的行（F列，索引为5）
        for (let i = 0; i < data.length; i++) {
            if (data[i][5] === plmCode) {
                targetRowIndex = i + 1; // 转换为1基索引
                break;
            }
        }

        if (targetRowIndex === -1) {
            throw new Error(`未找到 PLM Code: ${plmCode}`);
        }

        // 准备批量更新请求
        const requests = [];
        const formatRequests = [];
        
        // 定义日期列的索引（基于0的索引）
        const dateColumns = [8, 10, 11, 15]; // I, K, L, P列对应sampleReceivedDate, reviewFromDate, validateDate, closeDate
        const formattedCells = []; // 记录被格式化的单元格信息
        
        for (const [columnIndex, value] of Object.entries(updates)) {
            if (value !== undefined && value !== null) {
                const columnLetter = String.fromCharCode(65 + parseInt(columnIndex)); // 转换为列字母
                const cellRange = `${sheetName}!${columnLetter}${targetRowIndex}`;
                
                requests.push({
                    range: cellRange,
                    values: [[value]]
                });
                
                // 如果是日期列，添加格式化请求
                if (dateColumns.includes(parseInt(columnIndex))) {
                    formatRequests.push({
                        range: {
                            sheetId: await getSheetId(spreadsheetId, sheetName),
                            startRowIndex: targetRowIndex - 1,
                            endRowIndex: targetRowIndex,
                            startColumnIndex: parseInt(columnIndex),
                            endColumnIndex: parseInt(columnIndex) + 1
                        },
                        format: {
                            numberFormat: {
                                type: 'DATE',
                                pattern: 'yyyy-mm-dd'
                            }
                        }
                    });
                    
                    // 记录格式化的单元格信息
                    formattedCells.push({
                        sheet: sheetName,
                        cell: `${columnLetter}${targetRowIndex}`,
                        value: value
                    });
                }
            }
        }

        if (requests.length > 0) {
            // 执行批量更新
            const batchUpdateResponse = await sheets.spreadsheets.values.batchUpdate({
                spreadsheetId: spreadsheetId,
                resource: {
                    valueInputOption: 'USER_ENTERED',
                    data: requests
                }
            });

            // 如果有日期格式化请求，执行格式化
            if (formatRequests.length > 0) {
                await sheets.spreadsheets.batchUpdate({
                    spreadsheetId: spreadsheetId,
                    resource: {
                        requests: formatRequests.map(formatRequest => ({
                            repeatCell: {
                                range: formatRequest.range,
                                cell: {
                                    userEnteredFormat: formatRequest.format
                                },
                                fields: 'userEnteredFormat.numberFormat'
                            }
                        }))
                    }
                });
                
                // 为每个格式化的单元格打印详细日志
                formattedCells.forEach(cellInfo => {
                    console.log(`单元格 ${cellInfo.sheet}!${cellInfo.cell} 已成功格式化为日期格式 (yyyy-mm-dd)，值: ${cellInfo.value}`);
                });
                
                console.log(`日期格式化完成，总共格式化了 ${formatRequests.length} 个日期单元格`);
            }

            console.log(`成功更新 ${requests.length} 个单元格`);
            return batchUpdateResponse.data;
        } else {
            console.log('没有需要更新的数据');
            return null;
        }
    } catch (error) {
        console.error('更新部分列数据失败:', error.message);
        throw error;
    }
}

// 获取用户设置（模拟函数，实际应该从配置文件或其他地方获取）
// 获取sheet的ID（数字ID，不是名称）
async function getSheetId(spreadsheetId, sheetName) {
    try {
        const response = await sheets.spreadsheets.get({
            spreadsheetId: spreadsheetId
        });
        
        const sheet = response.data.sheets.find(s => s.properties.title === sheetName);
        if (!sheet) {
            throw new Error(`未找到名为 "${sheetName}" 的工作表`);
        }
        
        return sheet.properties.sheetId;
    } catch (error) {
        console.error('获取sheet ID失败:', error.message);
        throw error;
    }
}

async function getUserSettings() {
    try {
        // 暂时返回默认值
        return {
            email: 'user@example.com',
            site: 'Default Site'
        };
    } catch (error) {
        console.error('获取用户设置失败:', error.message);
        return {
            email: '',
            site: ''
        };
    }
}

module.exports = {
    initializeGoogleSheetsAPI,
    getSheetNames,
    readRowData,
    updatePartialColumns,
    getUserSettings,
    sendMonitoringData
};